package com.sitanyun.merchant.guide.frament.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.adapter.AnalysDiailsAdapter;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.bean.AnalysDialsBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * customerpage
 * 用户分析详情
 */
public class AnalysDiailsActivity extends BaseActivity {

    @BindView(R.id.tv_shars)
    TextView tvShars;
    @BindView(R.id.tv_browses)
    TextView tvBrowses;
    @BindView(R.id.tv_zuijin)
    TextView tvZuijin;
    @BindView(R.id.tv_yesterdays)
    TextView tvYesterday;
    @BindView(R.id.rv_analy)
    RecyclerView rvAnaly;
    @BindView(R.id.sw_analy)
    SwipeRefreshLayout swAnaly;
    @BindView(R.id.ll_one)
    LinearLayout llOne;
    @BindView(R.id.ll_todaytwo)
    LinearLayout llTodaytwo;
    private PopupWindow popupWindow;
    // 分页
    private int offset = 1;
    private String type;
    private String blos;
    private ArrayList<AnalysDialsBean.DataBean.RecordsBean> orderbeanlist;
    private AnalysDiailsAdapter analysDiailsAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_analys_diails;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("用户数据");
        //用户分析详情获取数据
        offset = 1;
        type = "0";
        blos = "1";
        initokhttps(type, blos);
    }

    @Override
    public void initView() {
        //创建布局管理
        orderbeanlist = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(AnalysDiailsActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvAnaly.setLayoutManager(layoutManager);
        //创建适配器
        analysDiailsAdapter = new AnalysDiailsAdapter(AnalysDiailsActivity.this);
        rvAnaly.setAdapter(analysDiailsAdapter);
        analysDiailsAdapter.notifyDataSetChanged();

        //刷新
        swAnaly.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //进行刷新判断
                offset = 1;
                if (tvYesterday.getText().toString().equals("昨天")) {
                    type = "0";
                } else if (tvYesterday.getText().toString().equals("近一周")) {
                    type = "1";
                } else if (tvYesterday.getText().toString().equals("近一个月")) {
                    type = "2";
                } else if (tvYesterday.getText().toString().equals("近一年")) {
                    type = "3";
                }
                //  blos ="1";
                initokhttps(type, blos);
            }
        });
        //加载更多
        analysDiailsAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                offset++;
                if (tvYesterday.getText().toString().equals("昨天")) {
                    type = "0";
                } else if (tvYesterday.getText().toString().equals("近一周")) {
                    type = "1";
                } else if (tvYesterday.getText().toString().equals("近一个月")) {
                    type = "2";
                } else if (tvYesterday.getText().toString().equals("近一年")) {
                    type = "3";
                }
                // blos ="1";
                initokhttps(type, blos);
            }
        });
        /**
         * 点击事件
         */
        analysDiailsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(AnalysDiailsActivity.this, AnalysDialsuserActivity.class)
                        .putExtra("cid", orderbeanlist.get(position).getCid() + "")
                        .putExtra("cname", orderbeanlist.get(position).getUsername() + "")
                );
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //请求数据
    private void initokhttps(String type, String blos) {

        OkHttpUtils.post()
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                .url(Urls.customerpage + "?size=" + "10" + "&current=" + offset + "&timeType=" + type + "&orderType=" + blos)
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {
                swAnaly.setRefreshing(false);
            }

            @Override
            public void onResponse(String response, int id) {
                swAnaly.setRefreshing(false);
                AnalysDialsBean analysDialsBean = new Gson().fromJson(response, AnalysDialsBean.class);
                if (analysDialsBean.getCode() == 0) {
                       //第一页时
                    if (offset == 1) {
                        orderbeanlist.clear();
                        //加数据到适配器
                        analysDiailsAdapter.setNewData(analysDialsBean.getData().getRecords());
                        orderbeanlist.addAll(analysDialsBean.getData().getRecords());
                        analysDiailsAdapter.notifyDataSetChanged();
                        //无数据
                        if (analysDialsBean.getData().getRecords().size() == 0) {
                            llOne.setVisibility(View.GONE);
                            llTodaytwo.setVisibility(View.VISIBLE);
                            return;
                        } else {
                            llOne.setVisibility(View.VISIBLE);
                            llTodaytwo.setVisibility(View.GONE);
                        }
                    } else {
                        //orderbeanlist.addAll(orderBean.getData());
                        //底部没有数据时
                        if (analysDialsBean.getData().getRecords().isEmpty()) {
                            analysDiailsAdapter.loadMoreEnd();
                        } else {
                            //滑动加载数据
                            List<AnalysDialsBean.DataBean.RecordsBean> data1 = analysDialsBean.getData().getRecords();
                            orderbeanlist.addAll(data1);
                            analysDiailsAdapter.addData(data1);
                            analysDiailsAdapter.notifyDataSetChanged();
                            analysDiailsAdapter.loadMoreComplete();

                        }

                    }
                }
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.tv_shars, R.id.tv_browses, R.id.tv_zuijin, R.id.tv_yesterdays})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //分享
            case R.id.tv_shars:
                offset = 1;
                if (tvYesterday.getText().toString().equals("昨天")) {
                    type = "0";
                } else if (tvYesterday.getText().toString().equals("近一周")) {
                    type = "1";
                } else if (tvYesterday.getText().toString().equals("近一个月")) {
                    type = "2";
                } else if (tvYesterday.getText().toString().equals("近一年")) {
                    type = "3";
                }
                blos = "1";
                initokhttps(type, blos);
                tvShars.setTextColor(Color.parseColor("#ff4d6eef"));
                tvBrowses.setTextColor(Color.parseColor("#ff333333"));
                tvZuijin.setTextColor(Color.parseColor("#ff333333"));
                analysDiailsAdapter.notifyDataSetChanged();
                break;
                //浏览
            case R.id.tv_browses:
                offset = 1;
                if (tvYesterday.getText().toString().equals("昨天")) {
                    type = "0";
                } else if (tvYesterday.getText().toString().equals("近一周")) {
                    type = "1";
                } else if (tvYesterday.getText().toString().equals("近一个月")) {
                    type = "2";
                } else if (tvYesterday.getText().toString().equals("近一年")) {
                    type = "3";
                }
                blos = "2";
                initokhttps(type, blos);
                analysDiailsAdapter.notifyDataSetChanged();
                tvShars.setTextColor(Color.parseColor("#ff333333"));
                tvBrowses.setTextColor(Color.parseColor("#ff4d6eef"));
                tvZuijin.setTextColor(Color.parseColor("#ff333333"));
                break;
                //最近
            case R.id.tv_zuijin:
                offset = 1;
                if (tvYesterday.getText().toString().equals("昨天")) {
                    type = "0";
                } else if (tvYesterday.getText().toString().equals("近一周")) {
                    type = "1";
                } else if (tvYesterday.getText().toString().equals("近一个月")) {
                    type = "2";
                } else if (tvYesterday.getText().toString().equals("近一年")) {
                    type = "3";
                }
                blos = "3";
                analysDiailsAdapter.notifyDataSetChanged();
                initokhttps(type, blos);
                tvShars.setTextColor(Color.parseColor("#ff333333"));
                tvBrowses.setTextColor(Color.parseColor("#ff333333"));
                tvZuijin.setTextColor(Color.parseColor("#ff4d6eef"));
                break;
            //筛选
            case R.id.tv_yesterdays:
                initpopu(view);
                break;
        }
    }

    //日期选择
    private void initpopu(View view) {
        View contentView = LayoutInflater.from(AnalysDiailsActivity.this).inflate(
                R.layout.popu_scen, null);
        Button share = (Button) contentView.findViewById(R.id.share);
        Button browse = (Button) contentView.findViewById(R.id.browse);
        Button metting = (Button) contentView.findViewById(R.id.metting);
        Button time = (Button) contentView.findViewById(R.id.time);
        //分享数量
        share.setText("昨天");
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvYesterday.setText("昨天");
                ///    Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                offset = 1;
                initokhttps("0", blos);
                analysDiailsAdapter.notifyDataSetChanged();
                popupWindow.dismiss();
            }
        });
        //浏览数量
        browse.setText("近一周");
        browse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvYesterday.setText("近一周");
                ///     Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                offset = 1;
                initokhttps("1", blos);
                analysDiailsAdapter.notifyDataSetChanged();
                popupWindow.dismiss();
            }
        });
        //同屏讲解次数
        metting.setText("近一个月");
        metting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvYesterday.setText("近一个月");
                ///      Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                offset = 1;
                initokhttps("2", blos);
                analysDiailsAdapter.notifyDataSetChanged();
                popupWindow.dismiss();
            }
        });
        //上传时间
        time.setText("近一年");
        time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvYesterday.setText("近一年");
                ///       Glide.with(getActivity()).load(R.mipmap.down_item).into(scenFh);
                offset = 1;
                initokhttps("3", blos);
                analysDiailsAdapter.notifyDataSetChanged();
                popupWindow.dismiss();
            }
        });
        popupWindow = new PopupWindow(contentView,
                330, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss

            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.baise));

        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);

    }
}
